using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace MicrosoftFrance.MCS.EPM2007
{
    class AppLog
    {
        #region Properties
        private StreamWriter swLog;
        private string fileName;

        public StreamWriter SwLog
        {
            get { return swLog; }
        }

        public String FileName
        {
            get { return fileName; }
        }

        #endregion

        #region Constructors
        
        // create file with datetime stamp in current directory
        public AppLog()
        {
            fileName = "AutomateTS_" + GeneralHelper.FormatTimeLog() + ".log";
            try
            {
                swLog = new StreamWriter(Environment.CurrentDirectory + "\\" + fileName);
            }
            catch(UnauthorizedAccessException)
            {
                System.Threading.Thread.Sleep(1000);
                swLog = new StreamWriter(Environment.CurrentDirectory + "\\" + fileName);
            }
            Console.Title = "P12AutomateTS";
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.WindowHeight = 40;
            Console.WindowWidth = 100;
        }

        // try to open an existing file or create a new one
        public AppLog(string fileName)
        {
            try
            {
                swLog = new StreamWriter(Environment.CurrentDirectory + "\\" + fileName, true);
            }
            catch (UnauthorizedAccessException)
            {
                System.Threading.Thread.Sleep(1000);
                swLog = new StreamWriter(Environment.CurrentDirectory + "\\" + fileName);
            }
        }

        #endregion

        #region Methods
        public void WriteLine(string toWrite)
        {
            WriteLine(toWrite, true, true);
        }

        public void WriteLine(string toWrite, bool dateTime)
        {
            if (dateTime)
                swLog.WriteLine(DateTime.Now.ToLongTimeString() + " : " + toWrite);
            else
                swLog.WriteLine(toWrite);

            Console.WriteLine(toWrite);
        }

        public void WriteLine(string toWrite, bool dateTime, bool writeConsole)
        {
            if (dateTime)
                swLog.WriteLine(DateTime.Now.ToLongTimeString() + " : " + toWrite);
            else
                swLog.WriteLine(toWrite);

            if (writeConsole)
                Console.WriteLine(toWrite);
        }

        public static void WriteLine(StreamWriter sw, string toWrite)
        {
            sw.WriteLine(DateTime.Now.ToLongTimeString() + " : " + toWrite);
            Console.WriteLine(toWrite);
        }

        public void Close()
        {
            swLog.Close();
        }

        #endregion
    }
}
